package com.controller;

import com.util.json.Result;
import com.util.servlet.BaseController;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
import java.util.Random;
import java.util.UUID;

/**
 * 采用apache框架上传
 */
@WebServlet("/uploadFile")
public class UploadFile extends HttpServlet {
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String path = req.getSession().getServletContext().getRealPath("")+"\\file\\";
        String fn = "";

        DiskFileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload upload = new ServletFileUpload(factory);
        upload.setSizeMax(1024*1024);//限制文件容量
        //文件名
        String name = "";
        try {
            List<FileItem> fileList = upload.parseRequest(req);
            for(FileItem item:fileList){
                //非文字
                if(!item.isFormField()){
                    // "." 需要转义符
                    //获取后缀
                    String sffix = item.getName().split("\\.")[1];
                    //文件名+随机数
                     name = item.getName().split("\\.")[0]+ new Random().nextInt()+"."+sffix;
                    //发送给前端
                     item.write(new File(path,name));
                    PrintWriter writer = resp.getWriter();
                    writer.write(Result.success(name));
                    writer.flush();
                    writer.close();

                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }



    }

    public static void main(String[] args) {
        String s = "a.jpg";
        String[] a= s.split("\\.");
        for(String ss:a){
            System.out.println(ss);
        }

    }
}
